package tpsi.pong;

import java.util.HashMap;
import java.util.Random;
import java.util.Set;

public class GamesManager {
	private HashMap<String, Game> games;
	private int maxGameListCnt;

	public GamesManager() {
		this.games = new HashMap<String, Game>();
		this.maxGameListCnt = 100;
	}

	public Game createGame(String gameName) {
		Game game = null;
		if ((this.games.size() < this.maxGameListCnt)
				&& !this.games.containsKey(gameName)) {
			game = new Game();
			game.setName(gameName);
			this.games.put(gameName, game);
		}
		return game;
	}

	public Game createGame(String gameName, Player p) {
		Game game = null;
		if ((this.games.size() < this.maxGameListCnt)
				&& !this.games.containsKey(gameName)) {
			game = new Game(p);
			game.setName(gameName);
			this.games.put(gameName, game);
		}
		return game;
	}

	public void deleteGame(String gameName) {
		this.games.remove(gameName);
	}

	public Game getGame(String gameName) {
		Game g = this.games.get(gameName);
		if ((g != null) && (g.getPlayersCount() != 4))
			return g;
		return null;
	}

	public String getGamesMsg() {
		StringBuilder sb = new StringBuilder();
		sb.append("GAMES\n");
		if (this.games.size() > 0) {
			int cnt;
			if (this.maxGameListCnt > this.games.size())
				cnt = this.games.size();
			else
				cnt = this.maxGameListCnt;
			Random rand = new Random(System.currentTimeMillis());
			int r = rand.nextInt(cnt);
			Set<String> set = this.games.keySet();
			String[] names = new String[set.size()];
			set.toArray(names);
			for (int i = cnt - 1; i > 0; --i) {
				sb.append(names[(r + i) % names.length]);
				sb.append(":");
			}
			sb.append(names[(r) % names.length]);
		}
		return sb.toString();
	}

	public void setMaxGameListCnt(int maxGameListCnt) {
		this.maxGameListCnt = maxGameListCnt;
	}

	public int getMaxGameListCnt() {
		return maxGameListCnt;
	}
}
